package com.nsharmon.iBridge.beans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;

import com.nsharmon.iBridge.dao.EMF;
import com.nsharmon.iBridge.dao.entities.BridgeConvention;
import com.nsharmon.iBridge.dao.entities.User;

@ManagedBean
@SessionScoped
public class ConventionBean extends CollectionBean<BridgeConvention> {
    @ManagedProperty("#{identity}")
    private Identity identity;

    public ConventionBean() {
    	super(BridgeConvention.class);
    }
    
	public void setIdentity(Identity identity) {
		this.identity = identity;
	}

	protected List<BridgeConvention> loadCollection() {
		List<BridgeConvention> conventions = null;
		if(identity != null) {
			EntityManager entityManager = EMF.createEntityManager();
			conventions = new ArrayList<BridgeConvention>();
			try {
				User currentUser = identity.getCurrentUser();
				if(currentUser != null) {
					conventions = currentUser.getBridgeConventions();
				}
			} finally {
				entityManager.close();
			}
		}
		return conventions;
	}
	
	public void onNewAction(ActionEvent event) {
		newObject();
	}
	
	public void onSaveAction(ActionEvent event) {
		if(identity != null) {
			User currentUser = identity.getCurrentUser();
			getSelected().setUser(currentUser);
			currentUser.getBridgeConventions().add(getSelected());
			addSelected();
		}
	}	
}
